package com.basics.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.basics.api.response.UploadFileData;
import com.basics.common.exception.CustomException;
import com.basics.common.utils.DateUtils;
import com.basics.common.utils.IdUtils;
import com.basics.common.utils.StringUtils;
import com.basics.common.utils.oss.AliOSSUtil;
import com.basics.common.utils.oss.UpdateChunkFileData;
import com.basics.common.utils.oss.UploadChunkFileReq;
import com.basics.framework.web.domain.RestResult;
import com.basics.sys.entity.SysDict;
import com.basics.sys.entity.SysDictItem;
import com.basics.sys.service.SysDictItemService;
import com.basics.sys.service.SysDictService;
import com.obs.services.model.PutObjectResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Api(tags = "公共接口")
@RestController
@RequestMapping("/api/common")
public class CommonApiController extends BaseApiController {

    @Autowired
    private SysDictItemService sysDictItemService;
    @Autowired
    private SysDictService dictService;

    @PostMapping({"uploadImage"})
    @ApiOperation("上传文件")
    public RestResult<UploadFileData> uploadImage(@RequestParam("file") MultipartFile file
            , @RequestParam(value = "folder",required = false)String folder) {
        if (!file.isEmpty()) {
            String fileRealName = IdUtils.fastSimpleUUID();
            String[] str =file.getOriginalFilename().split("\\.");
            String image = str.length>1?("."+str[1]):".png";
            UploadFileData data = new UploadFileData();
            try {
                if(StringUtils.isEmpty(folder)){
                    folder = "user";
                }
                //String contentType = file.getContentType();
                //if(contentType != null && (contentType.startsWith("image/"))){
                    BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
                    if(bufferedImage!=null){
                        data.setWidth(bufferedImage.getWidth());
                        data.setHeight(bufferedImage.getHeight());
                    }
                //}
                image = AliOSSUtil.uploadInputSteam(folder+"/"+ DateUtils.dateTime()+"/" +fileRealName+image, file.getInputStream());
                image = "https://"+image;
                data.setUrl(image);
            } catch (Exception var5) {
                log.error("上传文件失败", var5);
                throw new CustomException("上传文件失败，请联系管理员");
            }
            return RestResult.success(data);
        } else {
            return RestResult.error("请选择文件");
        }
    }

    @PostMapping({"uploadImages"})
    @ApiOperation("多图片上传(files)")
    @ResponseBody
    public RestResult<List<UploadFileData>> uploadImages(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("files");
        if (CollectionUtils.isNotEmpty(files)) {
            Iterator var4 = files.iterator();
            List<UploadFileData> resList = new ArrayList<>();
            while(var4.hasNext()) {
                MultipartFile file = (MultipartFile)var4.next();
                if (!file.isEmpty()) {
                    String fileRealName =  IdUtils.fastSimpleUUID();
                    String[] str =file.getOriginalFilename().split("\\.");
                    String image = str.length>1?("."+str[1]):".png";

                    try {
                        UploadFileData data = new UploadFileData();
                        //String contentType = file.getContentType();
                        //if(contentType != null && (contentType.startsWith("image/"))){
                            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
                            if(bufferedImage!=null){
                                data.setWidth(bufferedImage.getWidth());
                                data.setHeight(bufferedImage.getHeight());
                            }
                        //}
                        image = AliOSSUtil.uploadInputSteam(fileRealName+image, file.getInputStream());
                        data.setUrl("https://" + image);
                        resList.add(data);
                    } catch (Exception var9) {
                        log.error("上传文件失败", var9);
                        throw new CustomException("上传文件失败，请联系管理员");
                    }

                }
            }

            return RestResult.success(resList);
        } else {
            return RestResult.error("请选择上传文件");
        }
    }

    @PostMapping("/uploadChunk")
    @ApiOperation("上传分片文件")
    public RestResult<UpdateChunkFileData> uploadChunk(@RequestParam String identifier,
                                                       @RequestParam String filename,
                                                       @RequestParam Integer chunkNumber,
                                                       @RequestParam Integer totalChunks,
                                                       @RequestParam Long chunkSize,
                                                       @RequestParam Long currentChunkSize,
                                                       @RequestParam(required = false) String uploadId,
                                                       @RequestParam(required = false) String dir,
                                                       @RequestParam MultipartFile file){
        return RestResult.success(AliOSSUtil.uploadChunk(new UploadChunkFileReq(identifier,filename
                ,totalChunks,chunkSize,chunkNumber
                ,currentChunkSize,uploadId,dir),file));
    }


    @GetMapping("/selectDictByCode")
    @ApiOperation("根据字典code获取字典项")
    public RestResult<List<SysDictItem>> selectDictByCode(@RequestParam("code")String code){
        SysDict dict = dictService.getOne(new QueryWrapper<SysDict>().eq("dict_code",code));
        if(dict==null){
            return RestResult.error("字典不存在");
        }
        return RestResult.success(sysDictItemService.list(new QueryWrapper<SysDictItem>().eq("dict_id",dict.getId()).eq("status",1).orderByAsc("sort_order")));
    }
}
